<template>
  <div class="container">
    <vxe-toolbar >
      <template #buttons>
        <el-form :inline="true" :model="formInline" class="formInline" @submit.native.prevent >
          <el-form-item label="搜索">
            <el-input v-model="filterValue" :placeholder="strings.defaultIfBlank(searchPlaceholder, '搜索')"
                      v-if="searchFieldArr && searchFieldArr.length > 0"
                      type="text"
                      @input="getFilterData"
            ></el-input>
          </el-form-item>

          <el-form-item :label="column.title" v-for="(column,index) in columns.filter(columnTmp => {return columnTmp.filter})" :key="index">
            <!--下拉框 使用options 取非编辑配置-->
            <el-select @change="changeDataFilter"  v-model="formInline[column.field]"  clearable filterable   v-if="(column.selectType && column.selectType =='ElSelect' && column.selectOptionsFun)">
              <el-option  v-for="dict in column.selectOptionsFun() "
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"/>
            </el-select>

            <!--下拉框 使用optionsFun-->
            <el-select @change="changeDataFilter"   v-model="formInline[column.field]" clearable filterable   v-else-if="column.editRender.name =='ElSelect' && column.editRender.optionsFun" >
              <el-option  v-for="dict in column.editRender.optionsFun({}) "
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"/>
            </el-select>

            <!--下拉框 使用options 取编辑配置-->
            <el-select @change="changeDataFilter"  v-model="formInline[column.field]"  clearable filterable   v-else-if="(column.editRender.name =='ElSelect' && column.editRender.options) || (column.editRender.nameFun && column.editRender.nameFun() =='ElSelect')">
              <el-option  v-for="dict in column.editRender.options "
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"/>
            </el-select>

            <!--开关-->
            <el-select @change="changeDataFilter"  v-model="formInline[column.field]" clearable filterable   v-else-if="column.editRender.name =='ElSwitch'" >
              <el-option  v-for="dict in dictYS "
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="reset">重置</el-button>
            <el-button type="" size="small" @click="exportData">导出</el-button>
            <el-button  v-for="(config,index) in buttonList" :key="index" v-if="!cpDisabled"
                        :type="config.type"
                        :icon="config.icon"
                        :size="strings.defaultIfBlank(config.size, 'small')"
                        :style="config.style"
                        :title="config.title"
                        @click="callUserFun(config, {})"
            >{{config.text}}</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-toolbar>

    <vxe-table
       :data="dataFilter"
       :edit-config="cpEditConfig"
       :maxHeight="maxHeight"
       auto-resize
       sync-resize
       stripe
       border
       header-align="center"
       highlight-current-row
       highlight-hover-row
       highlight-current-column
       highlight-hover-column
       show-overflow="title"
       style="width: 100%;"
       ref="tableStatic"
       :sort-config="{defaultSort: defaultSort}"
       :export-config="{}"
    >
      {{print('defaultSort', defaultSort)}}
      <vxe-table-column type="seq" width="50" fixed="left"></vxe-table-column>

      <vxe-table-column
        v-for="(column,index) in columns" :key="index"
        :field="column.field"
        :title="column.title"
        :minWidth="column.minWidth != undefined ? column.minWidth : null"
        :width="column.width != undefined ? column.width : null "
        :edit-render="column.editRender"
        :fixed="column.fixed"
        :formatter="column.formatter"
        :sortable="column.sortable"
      >
        <!--表头列-->
        <template #header="scope" >
          <el-tooltip class="item" effect="dark" :content="strings.defaultString(column.titleHelp,column.title)" placement="bottom" >
            <div>
              <span>{{column.title}}</span>
              <span v-if="column.showHelp"  style="    position: absolute; left: 5px;top: 5px;">?</span>
              <i v-if="column.editRender" class="el-icon-edit" style="    position: absolute; left: 15px;top: 9px;"></i>
            </div>
          </el-tooltip>

          <el-button v-if="!cpDisabled && column.headBtnList && column.headBtnList.length > 0"  v-for="(config,index) in column.headBtnList" :key="index"
                      :type="config.type"
                      :icon="config.icon"
                      :size="strings.defaultIfBlank(config.size, 'small')"
                      :style="config.style"
                      :title="config.title"
                      @click="callUserFun(config, scope)"
          >{{config.text}}</el-button>
        </template>

        <!--编辑插槽-->
        <template #edit="scope" v-if="column.editRender && ['ElSelect', 'ElSwitch', 'nameFun','ElInputNumber', 'ElInput'].includes(column.editRender.name) ">

          <!--下拉框 使用optionsFun-->
          <el-select  v-model="scope.row[column.field]" clearable filterable @change="elementChange(scope)"  v-if="column.editRender.name =='ElSelect' && column.editRender.optionsFun" >
            <el-option  v-for="(dict, index) in scope.column.editRender.optionsFun(scope) "
                       :key="index"
                       :label="dict.label"
                       :value="dict.value"/>
          </el-select>

          <!--下拉框 使用options-->
          <el-select  v-model="scope.row[column.field]" clearable filterable @change="elementChange(scope, column)"  v-else-if="(column.editRender.name =='ElSelect' && column.editRender.options) || (column.editRender.nameFun && column.editRender.nameFun(scope) =='ElSelect')">
            <el-option  v-for="(dict, index) in scope.column.editRender.options "
                       :key="index"
                       :label="dict.label"
                       :value="dict.value"/>
          </el-select>

          <!--开关-->
          <el-switch v-model="scope.row[column.field]"  active-color="#13ce66" inactive-color="#ff4949" @change="elementChange(scope, column)" v-else-if="column.editRender.name =='ElSwitch'"
          ></el-switch>

          <!--下拉弹框-->
          <FortenDataviewDown v-else-if="column.editRender.name =='FortenDataviewDown' || (column.editRender.nameFun && column.editRender.nameFun(scope) =='FortenDataviewDown')"
                              propDownType="form"
                              :propFlagDialog="true"
                              propFieldText="dict"
                              propClickType="input"
                              :propForm="scope.row"
                              :propPK="scope.row.name"
                              :propUserParam="{viewKey: 'system_dv_define',useMsg: '请选择数据视图'}"
                              @select-change="selectChange"
          ></FortenDataviewDown>

          <!--使用htmlFun渲染-->
          <!--<div v-html="column.editRender.htmlFun()" clearable filterable @change="elementChange(scope)"  v-if="column.editRender.name =='htmlFun' && column.editRender.htmlFun"></div>-->

          <!--文本框-->
          <el-input v-model="scope.row[column.field]" placeholder="请输入" @input="elementChange(scope, column)"  v-else-if="column.editRender.name =='ElInput'"></el-input>

          <!--数字框-->
          <el-input-number v-model="scope.row[column.field]"  @input="elementChange(scope, column)"  v-else-if="column.editRender.name =='ElInputNumber'"
            size="mini" controls-position="right"
           :min="column.editRender.attrs && column.editRender.attrs.min ? column.editRender.attrs.min :0"
           :max="column.editRender.attrs && column.editRender.attrs.max ? column.editRender.attrs.max :999"
          ></el-input-number>

        </template>

        <!--默认内容插槽 按钮-->
        <template #default="scope" v-if="column.slots && column.slots.default ">
          <div v-for="(config,index) in column.slots.default(scope)" :key="index" v-if="!cpDisabled" >
            <span class="span" v-if="config.showType == 'html'" v-html="config.value"></span>
            <el-button v-if="config.showType == 'button'"
                       :type="config.type"
                       :icon="config.icon"
                       :size="config.size"
                       :style="config.style"
                       :title="config.title"
                       @click="callUserFun(config, scope)"
            >{{config.text}}</el-button>
          </div>
        </template>

        <template slot-scope="scope" v-else-if="column.getValueClass != undefined">
          <span   v-html="getValue(column, scope.row)"  :class="getValueClass(column, scope.row)"></span>
        </template>
      </vxe-table-column>

      <vxe-table-column
        title="操作"
        fixed="right"
        :width="btnList.length * 80"
        v-if="!cpDisabled && btnList && btnList.length > 0"
        align="center"
      >
        <template #default="scope">
          <el-button  v-for="(config,index) in btnList" :key="index"
                      :type="config.type"
                     :icon="config.icon"
                     :size="strings.defaultIfBlank(config.size, 'small')"
                     :style="config.style"
                     :title="config.title"
                     @click="callUserFun(config, scope)"
          >{{config.text}}</el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
  </div>
</template>

<script>
/* eslint-disable*/
import VXETable from 'vxe-table'
import XEUtils from 'xe-utils'

// 格式金额，默认2位数
VXETable.formats.add('formatSwitch', ({cellValue}) => {
  if (!cellValue || global.strings.isBlank(cellValue) || ['false','0',0, false].includes(cellValue)) return '否'
  return '是'
})

export default {
  title:'vxe-table静态表格',
  name:'FortenVxetableStatic',
  props:['data','columns', 'btnList', 'maxHeight', 'pkName','searchFieldArr', 'searchPlaceholder',  'defaultSort', 'buttonList', 'disabled'],
  computed: {
    cpDisabled() {
      return this.disabled != undefined && this.disabled
    },
    cpEditConfig() {
      if (this.cpDisabled) {
        return {}
      }
      return {trigger: 'click', mode: 'row', showIcon: false}
    }
  },
  data() {
    return {
      //编辑配置
      //搜索值
      filterValue: '',
      //搜索表单
      formInline: {},
      //数据字典，是，否
      dictYS: [
        { label: '请选择', value: '' },
        { label: '是', value: true },
        { label: '否', value: false }
      ],

      //过滤后的数据
      dataFilter: []
    }
  },
  watch:{
    //数据变化后进行曹组
    data:{
      handler(newValue, oldValue) {
        this.getFilterData()
      },
    }
  },
  methods: {
    getFilterData() {
      const filterName = XEUtils.toValueString(this.strings.trimrl(this.filterValue)).trim().toLowerCase()
      this.dataFilter = this.data.filter(
        item => {
          let noHit = false

          //精确搜索
          Object.keys(this.formInline).forEach(key => {
            if (noHit) return false
            if  (this.strings.isNotBlank(this.formInline[key]))  {
              if (this.formInline[key] == false && (!item[key] || ['false','0',0].includes(item[key]))) {
                noHit = false
              }else {
                noHit = item[key] != this.formInline[key]
              }
            }
          })
          if (noHit) return false

          //模糊搜索
          if  (this.strings.isNotBlank(filterName))  {
            noHit = !this.searchFieldArr.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) != -1)
          }
          return !noHit
        }
      )
    },
    //调试信息
    print(remark, ob) {
    },

    //控件值变化后
    elementChange(scope, column) {
      this.$refs.tableStatic.updateStatus(scope)
      this.sortDefault(column)


      //指定了下一个编辑字段，暂未实现
      if (column.editRender && column.editRender.nextEditField) {
        //该方法不起作用

        let nextEditColumn = this.$refs.tableStatic.getColumnByField(column.editRender.nextEditField)
        let nextEditColumnIndex = this.$refs.tableStatic.getColumnIndex(nextEditColumn)
        let row = this.$refs.tableStatic.getRowById(scope.rowid)
        let rowTr = $(this.$refs.tableStatic.$el).find('tr[data-rowid ="'+scope.rowid+'"]')
        let nextTd = rowTr.children('td:eq('+nextEditColumnIndex+')')
        let nextInput = rowTr.find('.el-input__inner')
        // this.$refs.tableStatic.clearActived()
        // nextInput.focus()
        this.print('nextEditColumn', nextEditColumn)
        this.print('nextEditColumnIndex', nextEditColumnIndex)
        this.print('row', row)
        this.print('rowTr', rowTr)
        this.print('scope', scope)
        this.print('nextTd', nextTd)

        // this.$refs.tableStatic.setActiveCell(scope, column.editRender.nextEditField)
      }

      this.$emit('cellChange',{scope: scope,column: column})
    },

    //进行默认排序
    sortDefault(column) {

      if (column && !column.changeSort) return
      if (!this.defaultSort || !this.defaultSort.field || !this.defaultSort.order) return
      this.data.forEach(ob => {
        if (this.strings.isBlank(ob[this.defaultSort.field])) {
          ob[this.defaultSort.field] = 999
        }
      })

      this.$refs.tableStatic.clearSort(this.defaultSort.field)
      this.$refs.tableStatic.sort(this.defaultSort.field, this.defaultSort.order)
    },

    //回调函数
    callUserFun(config, scope) {
      this.print('callUserFun.config', config)
      this.print('callUserFun.scope', scope)
      this.print('callUserFun.pkName', this.pkName)
      switch (config.key) {
        case 'delete': //删除列
          this.$confirm('确定删除该列么?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.data = this.data.splice(this.data.findIndex(item => item[this.pkName] === scope.row[this.pkName]), 1)
          }).catch(() => {
          });
          break
      }

      this.$emit('userFun',{config: config,scope: scope})
    },

    //视图选择后
    selectChange({fieldText, row, propPK, that}) {
      let index = this.data.findIndex(ob => ob.name == propPK)
      if (index != -1) this.data[index].dict = row.viewKey
    },

    //重置
    reset() {
      this.filterValue = ''
      this.formInline = {}
      this.getFilterData()
    },

    //排序
    sort () {
      this.$refs.tableStatic.sort('name', 'asc')
    },

    //改变时间
    changeDataFilter() {
      this.getFilterData()
    },
    // 导出
    exportData() {
      this.$refs.tableStatic.openExport()
    },
    // 内容样式
    getValue(column, row) {
      let cellValue = row[column.field]
      if (
        (column.editRender && column.editRender.name && column.editRender.name.toLowerCase().indexOf('switch') != -1)
        || (column.formatter && column.formatter == 'formatSwitch')
      ) {
        if (!cellValue || global.strings.isBlank(cellValue) || ['false','0',0, false].includes(cellValue)) {
          return '否'
        }
        return '是'
      }

      return cellValue
    },
    // 内容样式
    getValueClass(column, row) {
      let classStr = 'div-NoWrap '
      if (column.getValueClass) {
        classStr += column.getValueClass(column, row)
      }
      return classStr
    }
  }
}
</script>

<style lang="scss" scoped>
  .container{
    height: auto !important;

    /deep/ .vxe-table{
      .el-input__inner{
        font-size: 13px !important;
        padding: 0px 3px !important;
      }

      .vxe-cell--sort{
        position: absolute;
        right: 2px;
        top: 14px;
      }
    }
    /deep/ .formInline{
      .el-input,.el-select{
        width: 150px;
      }
    }

  }
</style>
